package realms;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import java.util.HashSet;
import java.util.Set;
public class MyRealm extends AuthorizingRealm {
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)principalCollection.getPrimaryPrincipal() ;
        System.out.println(username + "********");
        System.out.println("授权!");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo() ;
        Set<String> set = new HashSet<String>() ;
        set.add("admin") ;
        set.add("teach") ;
        //角色
        info.setRoles(set);
        //
        Set<String> set1 = new  HashSet<String>() ;
        set1.add("user:create") ;
        info.setStringPermissions(set1);
        return info;
    }
    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //得到用户名和密码
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken ;
        String username = token.getUsername() ;
        String password = new String(token.getPassword()) ;
        if("admin".equals(username) && "123456".equals(password)){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,password,"xx") ;
            return info ;
        }
        return null;
    }
}
